/**
 * @Description: TODO
 * @author: gongth
 * @date: 2022年08月29日 14:19
 */
package me.zhengjie.weixin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.mi.old.StringUtil;
import me.zhengjie.utils.HttpClientUtils;
import org.apache.hc.core5.http.ParseException;

import java.io.IOException;

@Slf4j
public class WxTemplateUtil {

//    http请求方式: POST https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
    public static int sendTemplateMsg(String touser, WxTemplateAbstract template) throws IOException, ParseException {
        return sendTemplateMsg(touser,template,null);
    }
    public static int sendTemplateMsg(String touser, WxTemplateAbstract template, String url) throws IOException, ParseException {
        String accessToken = WxAccessTokenUtil.getAccessToken();
        if (!StringUtil.isEmpty(accessToken)) {
            String sendUrl = WeiXinConfig.apiUrl + "/cgi-bin/message/template/send?access_token=" + WxAccessTokenUtil.getAccessToken();

            JSONObject pjson = new JSONObject();
//            pjson.put("access_token",tokenJson.getString("access_token"));
            pjson.put("touser",touser);
            pjson.put("template_id",template.getTemplateId());
            if(!StringUtil.isEmpty(url)){
                pjson.put("url",url);
            }
            pjson.put("data",JSONObject.parseObject(JSON.toJSONString(template.getData())));
            String res = HttpClientUtils.sendPost(sendUrl, pjson.toString());

            log.info("发送微信模板消息：{}",res);
            JSONObject accessTokenJson = JSONObject.parseObject(res);
            if(accessTokenJson.containsKey("errcode")){
                return accessTokenJson.getInteger("errcode");
            }
        }
        return -1;
    }

}

   